import { useState, useEffect } from "react";
import {
  Card,
  List,
  Tag,
  Typography,
  Space,
  Pagination,
  Input,
  DatePicker,
  Select,
  Button,
  Form,
  AutoComplete,
  Modal,
  message,
  Checkbox,
  Popconfirm,
  Tabs,
  Cascader,
  Alert,
  Row,
  Col,
} from "antd";

const { Text } = Typography;
import { Link, useNavigate } from "react-router-dom";
import MDEditor from "@uiw/react-md-editor";
import {
  fetchArticles,
  increaseArticleView,
  createArticle,
  updateArticle,
  deleteArticle,
  batchDeleteArticles,
  generateTags,
  fetchArticleById,
} from "../api/articles";
import { getAllCategories } from "../api/category";
import { getSearchHistory } from "../api/search";
import { isAdmin } from "../utils/auth";
import { useTheme } from "../contexts/ThemeContext";
import dayjs from "dayjs";
import {
  SearchOutlined,
  HistoryOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  BulbOutlined,
  FileTextOutlined,
  ReloadOutlined,
} from "@ant-design/icons";

// 安全渲染函数，只允许 <em> 标签，其余转义
function renderHighlight(html) {
  if (!html) return "";
  return (
    html
      // 转义所有危险字符
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#39;")
      // 再把 &lt;em&gt; 和 &lt;/em&gt; 恢复成真正的 <em>
      .replace(/&lt;em&gt;/g, "<em>")
      .replace(/&lt;\/em&gt;/g, "</em>")
  );
}

export default function Articles() {
  const { isDarkMode } = useTheme();
  const [articles, setArticles] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [loading, setLoading] = useState(false);
  const [keyword, setKeyword] = useState("");
  const [dateRange, setDateRange] = useState([]); // [startDate, endDate]
  const [username, setUsername] = useState("");
  const [form] = Form.useForm();
  const navigate = useNavigate();

  // 搜索历史状态
  const [keywordHistory, setKeywordHistory] = useState([]);
  const [usernameHistory, setUsernameHistory] = useState([]);
  const [serverSearchHistory, setServerSearchHistory] = useState([]); // 服务器搜索历史

  // 新增/编辑模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingArticle, setEditingArticle] = useState(null);
  const [articleForm] = Form.useForm();

  // 文章表单中的分类选择状态
  const [selectedCategoryPath, setSelectedCategoryPath] = useState([]);

  // 批量删除状态
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  // 分类相关状态
  const [categories, setCategories] = useState([]); // 级联选择器用的数据（用于表单）
  const [originalCategories, setOriginalCategories] = useState([]); // 原始分类数据，用于标签页显示
  const [categoryPath, setCategoryPath] = useState([]); // 级联选择器的值（用于表单）
  const [currentCategory, setCurrentCategory] = useState("all"); // 当前选中的父分类
  const [currentSubCategory, setCurrentSubCategory] = useState("all"); // 当前选中的子分类
  const [categoryLoading, setCategoryLoading] = useState(false);

  // 防抖搜索函数
  const debouncedSearch = () => {
    // 触发useEffect重新执行
    setLoading(true);
  };

  // 存储搜索历史的key
  const KEYWORD_HISTORY_KEY = "articles_keyword_history";
  const USERNAME_HISTORY_KEY = "articles_username_history";

  // 初始化时加载搜索历史
  useEffect(() => {
    const savedKeywordHistory = localStorage.getItem(KEYWORD_HISTORY_KEY);
    const savedUsernameHistory = localStorage.getItem(USERNAME_HISTORY_KEY);

    if (savedKeywordHistory) {
      try {
        setKeywordHistory(JSON.parse(savedKeywordHistory));
      } catch (e) {
        setKeywordHistory([]);
      }
    }

    if (savedUsernameHistory) {
      try {
        setUsernameHistory(JSON.parse(savedUsernameHistory));
      } catch (e) {
        setUsernameHistory([]);
      }
    }

    // 加载分类数据
    loadCategories();

    // 加载服务器搜索历史
    loadServerSearchHistory();
  }, []);

  // 加载分类数据
  const loadCategories = async () => {
    try {
      setCategoryLoading(true);
      const response = await getAllCategories();
      if (response.code === 1 && response.data) {
        const originalData = response.data.list || [];
        console.log("加载的分类数据:", originalData);

        // 保存原始数据用于标签页显示
        setOriginalCategories(originalData);

        // 转换为级联选择器需要的数据格式（用于文章表单）
        const cascaderData = originalData.map((category) => ({
          value: category.id,
          label: category.name,
          children:
            category.subCategories?.map((subCategory) => ({
              value: subCategory.id,
              label: subCategory.name,
            })) || [],
        }));
        console.log("级联选择器数据:", cascaderData);
        setCategories(cascaderData);
      }
    } catch (error) {
      console.error("加载分类失败:", error);
      message.error("加载分类失败");
    } finally {
      setCategoryLoading(false);
    }
  };

  // 加载服务器搜索历史
  const loadServerSearchHistory = async () => {
    const userId = localStorage.getItem("userId");
    if (!userId) {
      return;
    }

    try {
      const history = await getSearchHistory(userId);
      console.log("服务器搜索历史:", history);
      // 只有当 history 存在且不为空数组时才设置，否则设置为空数组
      setServerSearchHistory(
        history && Array.isArray(history) && history.length > 0 ? history : []
      );
    } catch (error) {
      console.error("加载搜索历史失败:", error);
      // 不显示错误提示，避免打扰用户
      setServerSearchHistory([]);
    }
  };

  // 刷新文章列表数据
  const refreshArticles = () => {
    setTimeout(() => {
      setLoading(true);

      // 构建查询参数
      const searchParams = {
        page,
        size: pageSize,
        keyword: keyword || undefined,
        startDate:
          dateRange && dateRange[0]
            ? dayjs(dateRange[0]).format("YYYY-MM-DD HH:mm:ss")
            : undefined,
        endDate:
          dateRange && dateRange[1]
            ? dayjs(dateRange[1]).format("YYYY-MM-DD HH:mm:ss")
            : undefined,
        username: username || undefined,
      };

      // 根据当前选择的分类添加分类参数
      if (currentCategory !== "all") {
        searchParams.categoryName = currentCategory;
      }
      if (currentSubCategory !== "all") {
        searchParams.subCategoryName = currentSubCategory;
      }

      fetchArticles(searchParams)
        .then((res) => {
          console.log(res);
          // 新接口结构
          if (res && res.list && typeof res.total !== "undefined") {
            console.log("yeyeyeye");
            // 字段映射处理
            const mappedList = res.list.map((item) => ({
              ...item,
              categoryName: item.category_name || item.categoryName || "",
              subCategoryName:
                item.sub_category_name || item.subCategoryName || "",
              tags: Array.isArray(item.tags)
                ? item.tags
                : typeof item.tags === "string"
                ? item.tags
                    .split(/[,，]/)
                    .map((t) => t.trim())
                    .filter(Boolean)
                : [],
              createAt: item.create_at || item.createAt,
              updateAt: item.update_at || item.updateAt,
            }));
            setArticles(mappedList);
            setTotal(res.total);
          } else if (Array.isArray(res)) {
            setArticles(res);
            setTotal(res.length);
          } else {
            setArticles([]);
            setTotal(0);
          }
        })
        .catch((error) => {
          console.error("获取文章列表失败:", error);
          message.error(error.message || "获取文章列表失败");
          setArticles([]);
          setTotal(0);
        })
        .finally(() => setLoading(false));
    }, 500); // 增加延迟到500毫秒，防止刷新过快
  };

  useEffect(() => {
    setLoading(true);

    // 构建查询参数
    const searchParams = {
      page,
      size: pageSize,
      keyword: keyword || undefined,
      startDate:
        dateRange && dateRange[0]
          ? dayjs(dateRange[0]).format("YYYY-MM-DD HH:mm:ss")
          : undefined,
      endDate:
        dateRange && dateRange[1]
          ? dayjs(dateRange[1]).format("YYYY-MM-DD HH:mm:ss")
          : undefined,
      username: username || undefined,
    };

    // 根据当前选择的分类添加分类参数
    if (currentCategory !== "all") {
      searchParams.category_name = currentCategory;
    }
    if (currentSubCategory !== "all") {
      searchParams.sub_category_name = currentSubCategory;
    }

    fetchArticles(searchParams)
      .then((res) => {
        console.log(res);
        if (res && res.list && typeof res.total !== "undefined") {
          console.log("yeyeye");
          // 字段映射处理
          const mappedList = res.list.map((item) => ({
            ...item,
            categoryName: item.category_name || item.categoryName || "",
            subCategoryName:
              item.sub_category_name || item.subCategoryName || "",
            tags: Array.isArray(item.tags)
              ? item.tags
              : typeof item.tags === "string"
              ? item.tags
                  .split(/[,，]/)
                  .map((t) => t.trim())
                  .filter(Boolean)
              : [],
            createAt: item.create_at || item.createAt,
            updateAt: item.update_at || item.updateAt,
          }));
          setArticles(mappedList);
          setTotal(res.total);
        } else if (Array.isArray(res)) {
          setArticles(res);
          setTotal(res.length);
        } else {
          setArticles([]);
          setTotal(0);
        }
      })
      .catch((error) => {
        console.error("获取文章列表失败:", error);
        message.error(error.message || "获取文章列表失败");
        setArticles([]);
        setTotal(0);
      })
      .finally(() => setLoading(false));
  }, [
    page,
    pageSize,
    keyword,
    dateRange,
    username,
    currentCategory,
    currentSubCategory,
  ]);

  // 当分类数据加载完成且正在编辑文章时，重新设置分类路径
  useEffect(() => {
    if (
      editingArticle &&
      originalCategories.length > 0 &&
      editingArticle.subCategoryId
    ) {
      const categoryPath = findCategoryPath(editingArticle.subCategoryId);
      if (categoryPath.length > 0) {
        console.log("分类数据加载完成，重新设置分类路径:", categoryPath);
        articleForm.setFieldsValue({ categoryPath });
      }
    }
  }, [originalCategories, editingArticle]);

  // 保存搜索历史
  const saveSearchHistory = (searchTerm, historyType) => {
    if (!searchTerm) return;

    const historyKey =
      historyType === "keyword" ? KEYWORD_HISTORY_KEY : USERNAME_HISTORY_KEY;
    const currentHistory =
      historyType === "keyword" ? keywordHistory : usernameHistory;
    const setHistory =
      historyType === "keyword" ? setKeywordHistory : setUsernameHistory;

    let newHistory = [...currentHistory];

    // 如果已存在，先移除
    newHistory = newHistory.filter((item) => item !== searchTerm);

    // 添加到开头
    newHistory.unshift(searchTerm);

    // 最多保存10条历史记录
    newHistory = newHistory.slice(0, 10);

    setHistory(newHistory);
    localStorage.setItem(historyKey, JSON.stringify(newHistory));
  };

  // 清空搜索历史
  const clearSearchHistory = (historyType) => {
    const historyKey =
      historyType === "keyword" ? KEYWORD_HISTORY_KEY : USERNAME_HISTORY_KEY;
    const setHistory =
      historyType === "keyword" ? setKeywordHistory : setUsernameHistory;

    setHistory([]);
    localStorage.removeItem(historyKey);
  };

  // 生成搜索建议选项 - 只显示服务器历史
  const getSearchOptions = (history, historyType) => {
    // 如果是关键词搜索，只显示服务器历史
    let displayHistory = [];
    if (historyType === "keyword") {
      // 只有服务器历史存在且不为空时才显示
      displayHistory =
        serverSearchHistory && serverSearchHistory.length > 0
          ? serverSearchHistory.slice(0, 10)
          : [];
    } else {
      // 其他类型（如用户名）显示本地历史
      displayHistory = history;
    }

    return displayHistory.map((item, index) => ({
      value: item,
      label: (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}>
          <span>
            <HistoryOutlined style={{ marginRight: 8, color: "#999" }} />
            {item}
          </span>
        </div>
      ),
    }));
  };

  // 自定义下拉渲染
  const getDropdownRender = (menu, historyType, history) => {
    return <div>{menu}</div>;
  };

  // 处理文章点击事件
  const handleArticleClick = async (articleId, event) => {
    event.preventDefault(); // 阻止默认的链接跳转

    try {
      // 先调用增加阅读量的接口
      await increaseArticleView(articleId);
      // 增加阅读量成功后，跳转到文章详情页
      navigate(`/article/${articleId}`);

      // 可选：更新本地文章列表中的阅读量（乐观更新）
      setArticles((prevArticles) =>
        prevArticles.map((article) =>
          article.id === articleId
            ? { ...article, views: (article.views || 0) + 1 }
            : article
        )
      );
    } catch (error) {
      console.error("增加阅读量失败:", error);
      message.error(error.message || "增加阅读量失败");
      // 即使增加阅读量失败，也要跳转到文章详情页
      navigate(`/article/${articleId}`);
    }
  };

  // 打开新增/编辑模态框
  const handleOpenModal = async (article = null) => {
    setEditingArticle(article);
    setIsModalVisible(true);

    if (article) {
      try {
        // 从后端获取完整的文章详情数据
        const fullArticleData = await fetchArticleById(article.id);
        console.log("获取的完整文章数据:", fullArticleData);

        if (fullArticleData) {
          // 使用从后端获取的完整数据
          setEditingArticle(fullArticleData);

          // 设置基本字段
          articleForm.setFieldsValue({
            title: fullArticleData.title,
            content: fullArticleData.content,
            tags: fullArticleData.tags, // 直接使用数组格式
            status: fullArticleData.status || 0,
            username: fullArticleData.username || "",
          });

          // 如果有子分类ID，查找对应的分类路径
          if (fullArticleData.subCategoryId && originalCategories.length > 0) {
            const categoryPath = findCategoryPath(
              fullArticleData.subCategoryId
            );
            console.log("找到的分类路径:", categoryPath);
            if (categoryPath.length > 0) {
              articleForm.setFieldsValue({ categoryPath });
            }
          }
        }
      } catch (error) {
        console.error("获取文章详情失败:", error);
        message.error("获取文章详情失败");
        // 如果获取失败，使用列表中的数据作为fallback
        articleForm.setFieldsValue({
          title: article.title,
          content: article.content,
          tags: article.tags,
          status: article.status || 0,
          username: article.username || "",
        });
      }
    } else {
      // 新增文章
      articleForm.resetFields();
      articleForm.setFieldsValue({
        status: 0,
        username: "",
      });
    }
  };

  // 查找分类路径的辅助函数
  const findCategoryPath = (subCategoryId) => {
    if (!subCategoryId || !originalCategories.length) return [];

    for (const category of originalCategories) {
      const subCategory = category.subCategories?.find(
        (sub) => sub.id === subCategoryId
      );
      if (subCategory) {
        return [category.id, subCategory.id];
      }
    }
    return [];
  };

  // 关闭模态框
  const handleCloseModal = () => {
    setIsModalVisible(false);
    setEditingArticle(null);
    setSelectedCategoryPath([]);
    articleForm.resetFields();
  };

  // 保存文章
  const handleSaveArticle = async (values) => {
    try {
      const articleData = {
        title: values.title,
        content: values.content,
        tags: Array.isArray(values.tags) ? values.tags.join(",") : values.tags, // 将数组转换为逗号分隔的字符串
        status: values.status,
        username: values.username,
      };

      // 如果选择了分类路径，使用新的子分类ID；否则保持原有的子分类ID
      if (values.categoryPath && values.categoryPath.length === 2) {
        articleData.subCategoryId = values.categoryPath[1];
      } else if (editingArticle && editingArticle.subCategoryId) {
        // 编辑模式下，如果没有选择新的分类，保持原有的子分类ID
        articleData.subCategoryId = editingArticle.subCategoryId;
      }

      if (editingArticle) {
        // 编辑
        await updateArticle({ ...articleData, id: editingArticle.id });
        message.success("文章更新成功");
      } else {
        // 新增
        await createArticle(articleData);
        message.success("文章创建成功");
      }

      handleCloseModal();
      // 延迟刷新数据，等待ES同步
      refreshArticles();
    } catch (error) {
      console.error("保存文章失败:", error);
      message.error(error.message || "操作失败，请重试");
    }
  };

  // 删除单个文章
  const handleDeleteArticle = async (id) => {
    try {
      await deleteArticle(id);
      message.success("文章删除成功");
      // 延迟刷新数据，等待ES同步
      refreshArticles();
    } catch (error) {
      console.error("删除文章失败:", error);
      message.error(error.message || "删除文章失败，请重试");
    }
  };

  // 批量删除文章
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请先选择要删除的文章");
      return;
    }

    try {
      await batchDeleteArticles(selectedRowKeys.join(","));
      message.success(`成功删除 ${selectedRowKeys.length} 篇文章`);
      setSelectedRowKeys([]);
      // 延迟刷新数据，等待ES同步
      refreshArticles();
    } catch (error) {
      console.error("批量删除失败:", error);
      message.error(error.message || "批量删除失败，请重试");
    }
  };

  // 处理批量选择
  const handleSelectChange = (articleId, checked) => {
    if (checked) {
      setSelectedRowKeys([...selectedRowKeys, articleId]);
    } else {
      setSelectedRowKeys(selectedRowKeys.filter((id) => id !== articleId));
    }
  };

  // 全选/取消全选
  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedRowKeys(articles.map((article) => article.id));
    } else {
      setSelectedRowKeys([]);
    }
  };

  // 根据文章内容生成标签
  const handleGenerateTags = async () => {
    const content = articleForm.getFieldValue("content");
    if (!content || content.trim() === "") {
      message.warning("请先输入文章内容");
      return;
    }

    try {
      const response = await generateTags(content);
      if (response.code === 1 && response.data) {
        // 将返回的标签字符串转换为数组
        const generatedTags = response.data.split(",").map((tag) => tag.trim());
        // 获取当前已有的标签
        const currentTags = articleForm.getFieldValue("tags") || [];
        // 合并标签并去重
        const allTags = [...new Set([...currentTags, ...generatedTags])];
        // 设置到表单
        articleForm.setFieldsValue({ tags: allTags });
        message.success("标签生成成功");
      } else {
        message.error(response.msg || "标签生成失败");
      }
    } catch (error) {
      console.error("生成标签失败:", error);
      message.error(error.message || "标签生成失败，请重试");
    }
  };

  // 处理父分类标签页切换
  const handleCategoryChange = (categoryKey) => {
    setCurrentCategory(categoryKey);
    setCurrentSubCategory("all"); // 重置子分类为全部
    setPage(1); // 重置页码
  };

  // 处理子分类标签页切换
  const handleSubCategoryChange = (subCategoryKey) => {
    setCurrentSubCategory(subCategoryKey);
    setPage(1); // 重置页码
  };

  // 获取当前选中父分类的子分类列表
  const getCurrentSubCategories = () => {
    if (currentCategory === "all") {
      return [];
    }
    const selectedCategory = originalCategories.find(
      (cat) => cat.name === currentCategory
    );
    return selectedCategory?.subCategories || [];
  };

  // 处理级联选择器变化（用于文章表单）
  const handleCascaderChange = (value) => {
    setCategoryPath(value || []);
    // 重置页码到第一页
    setPage(1);
    // 触发搜索
    debouncedSearch();
  };

  return (
    <div style={{ maxWidth: 1200, margin: "20px auto", padding: "0 16px" }}>
      {/* 页面标题 */}
      <div style={{ textAlign: "center", marginBottom: 32 }}>
        <Typography.Title
          level={2}
          style={{ color: "#1890ff", marginBottom: 8 }}>
          <FileTextOutlined /> {isAdmin() ? "文章管理" : "文章浏览"}
        </Typography.Title>
        <Typography.Text type="secondary" style={{ fontSize: 16 }}>
          基于 Spring Boot 和 Gin 服务的文章
          {isAdmin() ? "管理与智能搜索" : "浏览与智能搜索"}
        </Typography.Text>
      </div>

      <Card
        title={
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}>
            <span>文章列表</span>
            {/* 只有admin用户才能看到管理操作按钮 */}
            {isAdmin() && (
              <Space>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => handleOpenModal()}>
                  新增文章
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={refreshArticles}
                  loading={loading}
                  title="刷新文章列表">
                  刷新
                </Button>
                {articles.length > 0 && (
                  <Checkbox
                    checked={
                      selectedRowKeys.length > 0 &&
                      selectedRowKeys.length === articles.length
                    }
                    indeterminate={
                      selectedRowKeys.length > 0 &&
                      selectedRowKeys.length < articles.length
                    }
                    onChange={(e) => handleSelectAll(e.target.checked)}>
                    全选
                  </Checkbox>
                )}
                {selectedRowKeys.length > 0 && (
                  <Popconfirm
                    title="确定要删除选中的文章吗？"
                    onConfirm={handleBatchDelete}
                    okText="确定"
                    cancelText="取消">
                    <Button type="primary" danger icon={<DeleteOutlined />}>
                      删除选中 ({selectedRowKeys.length})
                    </Button>
                  </Popconfirm>
                )}
              </Space>
            )}
          </div>
        }
        style={{
          maxWidth: 1000,
          margin: "20px auto",
          borderRadius: 12,
          boxShadow: isDarkMode
            ? "0 2px 12px rgba(0,0,0,0.3)"
            : "0 2px 12px #eee",
          backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
          borderColor: isDarkMode ? "#434343" : "#d9d9d9",
          transition: "all 0.3s ease",
        }}>
        {/* 搜索框 - 单独的Card */}
        <Card
          size="small"
          style={{
            marginBottom: 24,
            backgroundColor: isDarkMode ? "#262626" : "#fafbfc",
            borderColor: isDarkMode ? "#434343" : "#e8e8e8",
            border: `1px solid ${isDarkMode ? "#434343" : "#e8e8e8"}`,
            borderRadius: 8,
          }}
          title={
            <Space>
              <SearchOutlined />
              <span>搜索条件</span>
            </Space>
          }>
          <Form
            form={form}
            layout="inline"
            initialValues={{ keyword, dateRange, username }}
            onFinish={({ keyword, dateRange, username }) => {
              const trimmedKeyword = keyword?.trim() || "";
              const trimmedUsername = username?.trim() || "";

              // 保存搜索历史
              if (trimmedKeyword) {
                saveSearchHistory(trimmedKeyword, "keyword");
              }
              if (trimmedUsername) {
                saveSearchHistory(trimmedUsername, "username");
              }

              setKeyword(trimmedKeyword);
              setDateRange(dateRange || []);
              setUsername(trimmedUsername);
              setPage(1);
            }}>
            {/* 第一行：关键词搜索 */}
            <Row gutter={[12, 12]} style={{ width: "100%" }}>
              <Col xs={24}>
                <Form.Item
                  name="keyword"
                  style={{ marginBottom: 0, width: "100%" }}>
                  <AutoComplete
                    options={getSearchOptions(keywordHistory, "keyword")}
                    filterOption={false}
                    onFocus={() => {
                      // 每次获得焦点时重新获取服务器搜索历史
                      loadServerSearchHistory();
                    }}
                    dropdownRender={(menu) =>
                      getDropdownRender(menu, "keyword", keywordHistory)
                    }
                    style={{ width: "100%" }}>
                    <Input
                      placeholder="请输入关键词"
                      allowClear
                      style={{ width: "100%" }}
                      prefix={<SearchOutlined />}
                    />
                  </AutoComplete>
                </Form.Item>
              </Col>
            </Row>

            {/* 第二行：其他条件 */}
            <Row gutter={[12, 12]} style={{ marginTop: 12, width: "100%" }}>
              <Col xs={24} sm={12} md={8}>
                <Form.Item
                  name="dateRange"
                  style={{ marginBottom: 0, width: "100%" }}>
                  <DatePicker.RangePicker
                    style={{ width: "100%" }}
                    allowClear
                    showTime={{ format: "HH:mm:ss" }}
                    format="YYYY-MM-DD HH:mm:ss"
                    placeholder={["开始时间", "结束时间"]}
                  />
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={8}>
                <Form.Item
                  name="username"
                  style={{ marginBottom: 0, width: "100%" }}>
                  <AutoComplete
                    options={getSearchOptions(usernameHistory, "username")}
                    filterOption={false}
                    dropdownRender={(menu) =>
                      getDropdownRender(menu, "username", usernameHistory)
                    }
                    style={{ width: "100%" }}>
                    <Input
                      allowClear
                      placeholder="请输入用户名"
                      style={{ width: "100%" }}
                      prefix={<SearchOutlined />}
                    />
                  </AutoComplete>
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={8}>
                <Form.Item style={{ marginBottom: 0, width: "100%" }}>
                  <Space style={{ width: "100%" }}>
                    <Button type="primary" htmlType="submit">
                      搜索
                    </Button>
                    <Button
                      htmlType="button"
                      onClick={() => {
                        form.resetFields();
                        setKeyword("");
                        setDateRange([]);
                        setUsername("");
                        setPage(1);
                      }}>
                      重置
                    </Button>
                  </Space>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        {/* 分类选择 - CSDN风格 */}
        <div style={{ marginBottom: 24, overflow: "auto" }}>
          {/* 父分类选择 */}
          <div
            style={{
              display: "flex",
              gap: 16,
              alignItems: "center",
              whiteSpace: "nowrap",
              paddingBottom: 8,
              overflowX: "auto",
              WebkitOverflowScrolling: "touch",
            }}>
            <Button
              type="text"
              onClick={() => {
                setCurrentCategory("all");
                setCurrentSubCategory("all");
                setPage(1);
              }}
              style={{
                fontWeight: currentCategory === "all" ? "bold" : "normal",
                color:
                  currentCategory === "all"
                    ? "#1890ff"
                    : isDarkMode
                    ? "#bfbfbf"
                    : "#666",
                fontSize: 14,
                padding: "0 4px",
                height: "auto",
                transition: "all 0.3s",
                flexShrink: 0,
              }}>
              全部
            </Button>
            {originalCategories.map((category) => (
              <Button
                key={category.name}
                type="text"
                onClick={() => {
                  setCurrentCategory(category.name);
                  setCurrentSubCategory("all");
                  setPage(1);
                }}
                style={{
                  fontWeight:
                    currentCategory === category.name ? "bold" : "normal",
                  color:
                    currentCategory === category.name
                      ? "#1890ff"
                      : isDarkMode
                      ? "#bfbfbf"
                      : "#666",
                  fontSize: 14,
                  padding: "0 4px",
                  height: "auto",
                  transition: "all 0.3s",
                  flexShrink: 0,
                }}>
                {category.name}
              </Button>
            ))}
          </div>

          {/* 子分类选择 */}
          {currentCategory !== "all" &&
            getCurrentSubCategories().length > 0 && (
              <div
                style={{
                  display: "flex",
                  gap: 12,
                  alignItems: "center",
                  whiteSpace: "nowrap",
                  marginTop: 8,
                  overflowX: "auto",
                  WebkitOverflowScrolling: "touch",
                  paddingBottom: 4,
                }}>
                <Button
                  type="text"
                  size="small"
                  onClick={() => {
                    setCurrentSubCategory("all");
                    setPage(1);
                  }}
                  style={{
                    fontWeight:
                      currentSubCategory === "all" ? "bold" : "normal",
                    color:
                      currentSubCategory === "all"
                        ? "#1890ff"
                        : isDarkMode
                        ? "#8c8c8c"
                        : "#999",
                    fontSize: 13,
                    padding: "0 4px",
                    height: "auto",
                    transition: "all 0.3s",
                    flexShrink: 0,
                  }}>
                  全部
                </Button>
                {getCurrentSubCategories().map((subCategory) => (
                  <Button
                    key={subCategory.name}
                    type="text"
                    size="small"
                    onClick={() => {
                      setCurrentSubCategory(subCategory.name);
                      setPage(1);
                    }}
                    style={{
                      fontWeight:
                        currentSubCategory === subCategory.name
                          ? "bold"
                          : "normal",
                      color:
                        currentSubCategory === subCategory.name
                          ? "#1890ff"
                          : isDarkMode
                          ? "#8c8c8c"
                          : "#999",
                      fontSize: 13,
                      padding: "0 4px",
                      height: "auto",
                      transition: "all 0.3s",
                      flexShrink: 0,
                    }}>
                    {subCategory.name}
                  </Button>
                ))}
              </div>
            )}
        </div>

        {/* 批量选择提示 */}
        {selectedRowKeys.length > 0 && (
          <Alert
            message={`已选择 ${selectedRowKeys.length} 篇文章`}
            type="info"
            showIcon
            closable
            onClose={() => setSelectedRowKeys([])}
            style={{ marginBottom: 16 }}
          />
        )}

        <List
          itemLayout="vertical"
          dataSource={articles}
          loading={loading}
          renderItem={(article) => (
            <List.Item
              key={article.id}
              extra={
                <Space direction="vertical" align="end">
                  <Typography.Text type="secondary">
                    浏览量：{article.views}
                  </Typography.Text>
                  {selectedRowKeys.length === 0 && isAdmin() && (
                    <Space>
                      <Button
                        type="text"
                        icon={<EditOutlined />}
                        size="small"
                        onClick={() => handleOpenModal(article)}
                        title="编辑文章"
                      />
                      <Popconfirm
                        title="确定要删除这篇文章吗？"
                        onConfirm={() => handleDeleteArticle(article.id)}
                        okText="确定"
                        cancelText="取消">
                        <Button
                          type="text"
                          icon={<DeleteOutlined />}
                          size="small"
                          danger
                          title="删除文章"
                        />
                      </Popconfirm>
                    </Space>
                  )}
                </Space>
              }>
              <List.Item.Meta
                avatar={
                  isAdmin() && (
                    <Checkbox
                      checked={selectedRowKeys.includes(article.id)}
                      onChange={(e) =>
                        handleSelectChange(article.id, e.target.checked)
                      }
                      style={{ marginTop: 8 }}
                    />
                  )
                }
                title={
                  <Typography.Title level={4} style={{ margin: 0 }}>
                    <a
                      href={`/article/${article.id}`}
                      onClick={(e) => handleArticleClick(article.id, e)}
                      style={{ color: "inherit", textDecoration: "none" }}
                      dangerouslySetInnerHTML={{
                        __html: renderHighlight(article.title),
                      }}
                    />
                  </Typography.Title>
                }
                description={
                  <>
                    <div
                      style={{
                        display: "flex",
                        alignItems: "center",
                        flexWrap: "wrap",
                      }}>
                      <Typography.Text>
                        作者：{article.username}
                      </Typography.Text>
                      <span style={{ marginLeft: 16 }}></span>
                      {article.tags.map((tag, index) => (
                        <Tag color="blue" key={index}>
                          <span
                            dangerouslySetInnerHTML={{
                              __html: renderHighlight(tag),
                            }}
                          />
                        </Tag>
                      ))}
                    </div>
                    <div style={{ marginTop: 2 }}>
                      <Typography.Text type="secondary">
                        分类：{article.categoryName || "-"}
                      </Typography.Text>
                      <span style={{ margin: "0 8px" }}></span>
                      <Typography.Text type="secondary">
                        子分类：{article.subCategoryName || "-"}
                      </Typography.Text>
                    </div>
                  </>
                }
              />
              {/* 预览时隐藏markdown格式，仅显示纯文本摘要 */}
              <Typography.Paragraph ellipsis={{ rows: 2, expandable: false }}>
                <span
                  dangerouslySetInnerHTML={{
                    __html: renderHighlight(
                      article.content
                        ? article.content
                            .replace(/[#*_`\-\[\]!\(\)\n\r]/g, "")
                            .slice(0, 100)
                        : ""
                    ),
                  }}
                />
              </Typography.Paragraph>
              <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                创建时间：
                {article.createAt
                  ? dayjs(article.createAt).format("YYYY-MM-DD HH:mm:ss")
                  : "-"}
                &emsp;&emsp;&emsp; 　 最后更新：
                {article.updateAt
                  ? dayjs(article.updateAt).format("YYYY-MM-DD HH:mm:ss")
                  : "-"}
              </Typography.Text>
            </List.Item>
          )}
        />
        <div style={{ textAlign: "center", marginTop: 24 }}>
          <Pagination
            current={page}
            pageSize={pageSize}
            total={total}
            showSizeChanger
            pageSizeOptions={["5", "10", "20", "50"]}
            onChange={(p, s) => {
              setPage(p);
              setPageSize(s);
            }}
            showTotal={(t) => `共 ${t} 条`}
          />
        </div>

        {/* 新增/编辑文章模态框 */}
        <Modal
          title={editingArticle ? "编辑文章" : "新增文章"}
          open={isModalVisible}
          onCancel={handleCloseModal}
          onOk={() => articleForm.submit()}
          width={600}
          okText="保存"
          cancelText="取消">
          <Form
            form={articleForm}
            layout="vertical"
            onFinish={handleSaveArticle}
            style={{ marginTop: 20 }}>
            <Form.Item
              name="title"
              label="文章标题"
              rules={[{ required: true, message: "请输入文章标题" }]}>
              <Input placeholder="请输入文章标题" />
            </Form.Item>
            <Form.Item
              name="content"
              label="文章内容 (支持Markdown)"
              rules={[{ required: true, message: "请输入文章内容" }]}>
              <MDEditor
                height={300}
                placeholder="请输入文章内容，支持Markdown语法"
              />
            </Form.Item>
            <Form.Item
              name="tags"
              label={
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span>文章标签</span>
                  <Button
                    type="link"
                    size="small"
                    icon={<BulbOutlined />}
                    onClick={handleGenerateTags}
                    style={{ padding: 0, height: "auto" }}
                    title="根据文章内容智能生成标签">
                    智能生成
                  </Button>
                </div>
              }
              rules={[{ required: true, message: "请输入文章标签" }]}>
              <Select
                mode="tags"
                placeholder="请输入标签并按回车添加，或点击右侧按钮智能生成"
                tokenSeparators={[","]}
                allowClear
                style={{ width: "100%" }}>
                {articles
                  .flatMap((article) => article.tags)
                  .filter((tag, index, arr) => arr.indexOf(tag) === index) // 去重
                  .map((tag) => (
                    <Select.Option key={tag} value={tag}>
                      {tag}
                    </Select.Option>
                  ))}
              </Select>
            </Form.Item>
            <Form.Item
              name="username"
              label="用户名"
              rules={[{ required: true, message: "请输入用户名" }]}>
              <Input placeholder="请输入用户名" />
            </Form.Item>

            <Form.Item name="categoryPath" label="文章分类">
              <Cascader
                options={categories}
                placeholder="请选择文章分类（可选）"
                changeOnSelect
                showSearch={{
                  filter: (inputValue, path) =>
                    path.some(
                      (option) =>
                        option.label
                          .toLowerCase()
                          .indexOf(inputValue.toLowerCase()) > -1
                    ),
                }}
                style={{ width: "100%" }}
              />
            </Form.Item>

            <Form.Item name="status" label="文章状态" initialValue={0}>
              <Select placeholder="请选择文章状态">
                <Select.Option value={0}>草稿</Select.Option>
                <Select.Option value={1}>已发布</Select.Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
}
